package recharge

import (
	"context"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/schema/recharge"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/pkg/xerrors"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/rpc"
	"github.com/jinzhu/copier"
	"gorm.io/gorm"
)

type RechargeSmsModel struct {
	ctx context.Context
	db  *gorm.DB
}

func NewRechargeSmsModel(ctx context.Context, db *gorm.DB) *RechargeSmsModel {
	return &RechargeSmsModel{
		ctx: ctx,
		db:  db,
	}
}
func (model *RechargeSmsModel) getDb() *gorm.DB {
	if model.db != nil {
		return model.db
	}
	return svc.Db
}

func (m *RechargeSmsModel) RechargeSmsListPage(in *rpc.RechargeSmsPageRequest) (*rpc.RechargeSmsPageResponse, error) {
	var rechargeSmsInfos []*recharge.RechargeSms
	offset := in.Page.PageSize * (in.Page.PageNo - 1)

	// 查询所有用户银行信息
	query := m.db.Model(recharge.RechargeSms{})

	if in.Param.UserId != 0 {
		query = query.Where("user_id = ?", in.Param.UserId)
	}
	if in.Param.OrderNo != "" {
		query = query.Where("order_no = ?", in.Param.OrderNo)
	}
	if in.Param.MatchStatus != "" {
		query = query.Where("match_status = ?", in.Param.MatchStatus)
	}
	if in.Param.ReceivingBank != "" {
		query = query.Where("receiving_bank = ?", in.Param.ReceivingBank)
	}
	if in.Param.ReceivingAccount != 0 {
		query = query.Where("receiving_account = ?", in.Param.ReceivingAccount)
	}
	if in.Param.SmsId != 0 {
		query = query.Where("sms_id = ?", in.Param.SmsId)
	}
	if in.Param.SmsType != 0 {
		query = query.Where("sms_type = ?", in.Param.SmsType)
	}
	if in.Param.Sender != 0 {
		query = query.Where("sender = ?", in.Param.Sender)
	}
	if in.Param.SmsContext != "" {
		query = query.Where("sms_context like ?", "%"+in.Param.SmsContext+"%")
	}
	if in.Param.SendTime != 0 {
		query = query.Where("send_time = ?", in.Param.SendTime)
	}

	var total int64
	_ = query.Count(&total).Error

	query = query.Limit(int(in.Page.PageSize)).Offset(int(offset))
	tx := query.Find(&rechargeSmsInfos)
	if tx.Error != nil {
		return nil, xerrors.ErrDataConvert
	}
	var rechargeSmsInfoList []*rpc.RechargeSmsInfo
	_ = copier.Copy(&rechargeSmsInfoList, rechargeSmsInfos)
	return &rpc.RechargeSmsPageResponse{
		DataList: rechargeSmsInfoList,
		Total:    total,
	}, nil
}
